<template>
  <div class="account-form-edit"
       v-loading="accountLoading">
    <div class="account-form-edit__header flex items-center justify-between">
      <el-input class="account-form-edit__header--account"
                :placeholder="$t('custom.attendance.record.search.search')"
                prefix-icon="el-icon-search"
                v-model="searchForm.accountName">
      </el-input>

      <AccountAction :ignore="['edit','delete','add']"
                     trigger="none"
                     v-if="template.usageCounter==0"
                     :template="template"
                     @success="handleSuccessAccount"
                     :loading.sync="accountLoading" />
    </div>

    <div class="account-form-edit__tree">
      <el-tree class="account-tree"
               ref="accountTree"
               draggable
               :props="accountTreeProps"
               :data="accountTreeData"
               highlight-current
               node-key="id"
               default-expand-all
               :allow-drop="allowDrop"
               @node-drag-end="handleDragEnd"
               :filter-node-method="filterAccountNode">
        <template v-slot="{ data }">
          <TreeNode :title="data.label">
            <template v-slot:action
                      v-if="template.usageCounter==0">
              <AccountAction :account="data"
                             :ignore="ignoreBtns(data)"
                             :template="template"
                             @success="handleSuccessAccount"
                             :loading.sync="accountLoading" />
            </template>
          </TreeNode>
        </template>
      </el-tree>
    </div>

    <div class="dialog-footer"
         v-if="template.modifyFlag">
      <el-button type="primary"
                 @click="handleSave">{{$t('custom.save')}}</el-button>
    </div>
  </div>
</template>

<script>
import { get } from 'lodash'
import TreeNode from './tree-node'
import AccountAction from './account-action'
import { accountTreeProps } from '../account-mapping.data'

export default {
  name: 'AccountFormEdit',
  props: {
    template: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    TreeNode,
    AccountAction
  },
  data () {
    return {
      accountTreeProps,
      accountLoading: false,
      accountTreeData: [],

      searchForm: {}
    }
  },

  mounted () {
    this.searchForm.accountId = this.$props.template.id
    this.getAccounts()
  },
  watch: {
    'searchForm.accountName': {
      handler (val) {
        this.$refs.accountTree.filter(val)
      }
    }
  },
  methods: {
    ignoreBtns (data) {
      const ignores = []
      if (data.children.length !== 0) {
        ignores.push('delete')
      }

      return [...ignores, 'add-top']
    },
    async getAccounts () {
      try {
        this.accountLoading = true
        const { requstAccountList } = this.$interface.mapping

        const { data: response } = await requstAccountList(this.searchForm)
        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }

        this.accountTreeData = get(response, 'data', [])
      } catch (error) {

      } finally {
        this.accountLoading = false
      }
    },

    filterAccountNode (value, data) {
      if (!value) {
        return true
      }
      return data.label.toLowerCase().indexOf(value.toLowerCase()) !== -1
    },

    allowDrop (draggingNode, dropNode) {
      if (draggingNode.data.pid === dropNode.data.pid) {
        return draggingNode
      }

      return false
    },

    handleDragEnd (draggingNode, endNode, position, event) {
      if (draggingNode.data.pid === endNode.data.pid && draggingNode.data.id !== endNode.data.id) {
        this.$refs.accountTree.remove(draggingNode.data)
        this.$refs.accountTree.insertBefore(draggingNode.data, endNode)
      }

      event.stopPropagation()
    },

    async handleSave () {
      try {
        this.accountLoading = true
        const { updateMappingItem } = this.$interface.mapping
        const params = {
          accountId: this.searchForm.accountId,
          items: this.accountTreeData
        }
        const { data: response } = await updateMappingItem(params)

        if (response.code !== 0) {
          throw get(response, 'msg', '')
        }
        this.$emit('success')
        this.$message.success(this.$t('success'))
      } catch (error) {
        this.$message.error(error)
      } finally {
        this.accountLoading = false
      }
    },
    handleSuccessAccount () {
      this.getAccounts()
    }
  }
}

</script>

<style lang="scss" scoped>
.account-form-edit {
  &__header {
    box-shadow: 0 1px 0 0 #f0f0f0;
    padding: 0 20px;
    height: 48px;
    margin-bottom: 1px;
    &--account {
      width: 180px;
    }
  }
  &__tree {
    padding: 0 20px;
    overflow: auto;
    height: 50vh;
    .account-tree {
      ::v-deep .el-tree-node__content {
        height: auto;
      }
    }
  }
}
</style>
